'use strict';
const uniPay = require('uni-pay')
const {
	wxConfigMp
} = uniPayConfig.requireFile('config.js')
exports.main = async (event, context) => {
	let {
		provider,
		openId,
		remark,
		order_id
	} = event

	// 判断订单是否存在，订单支付状态为未支付
	const orderList = await db.collection('orders').where({
		order_id
	}).get()

	if (orderList.data.length !== 1 || orderList.data[0].status !== 1) {
		return {
			code: -2,
			msg: '订单状态不正确'
		}
	}
	// 修改订单支付方式和插入订单备注
	await db.collection('orders').where({
		order_id
	}).update({
		payment_channel: provider,
		order_remark: remark
	})

	let uniPayInstance,
		notifyUrl =
		`https://8798e3c5-3cd6-4ecc-8b5c-f75aca13865b.bspapp.com/http/payment-notify/${provider}_${context.PLATFORM}`,
		openid,
		tradeType
	// notifyUrl为接收通知的云函数的url，务必替换为自己的通知地址，云函数Url化请参考：https://uniapp.dcloud.io/uniCloud/http
	switch (provider + '_' + context.PLATFORM) {
		case 'wxpay_mp-weixin':
			uniPayInstance = uniPay.initWeixin(wxConfigMp)
			openid = userInfo.wx_openid['mp-weixin']
			tradeType = 'JSAPI'
			break;
		case 'alipay_mp-alipay':
			uniPayInstance = uniPay.initAlipay(aliConfigMp)
			openid = userInfo.ali_openid
			break;
		case 'wxpay_app-plus':
			uniPayInstance = uniPay.initWeixin(wxConfigApp)
			tradeType = 'APP'
			break;
		case 'alipay_app-plus':
			uniPayInstance = uniPay.initAlipay(aliConfigApp)
			break;
		case 'wxpay_h5':
			uniPayInstance = uniPay.initWeixin(wxConfigH5)
			tradeType = 'NATIVE'
			break;
		case 'alipay_h5':
			uniPayInstance = uniPay.initAlipay(aliConfigH5)
			// uniPayInstance = uniPay.initAlipay(aliConfigSandbox)
			tradeType = 'NATIVE'
			break;
		default:
			return {
				code: -1,
					msg: '参数错误'
			}
	}

	const {
		totalFee
	} = orderList.data[0]
	// 支付提交
	let orderinfo

	try {
		// 获取支付信息
		orderInfo = await uniPayInstance.getOrderInfo({
			openid, // App端支付时不需要openid，传入个undefined也没有影响
			outTradeNo,
			totalFee,
			subject: "测试商城的测试订单标题",
			body: "测试商城的测试订单详情",
			notifyUrl,
			tradeType
		})
	} catch (e) {
		console.log(e.message)
		return {
			code: -3,
			msg: '获取支付信息失败，请稍后再试'
		}
	}

	return {
		outTradeNo,
		orderInfo
	}
};
